package com.example.rwq_test.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 写一个阻塞队列
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/12/22
 */
public class BlockingQueueExample {

    private Queue<Integer> queue = new LinkedList<>();
    private int capacity;

    public BlockingQueueExample (int capacity) {
        this.capacity = capacity;
    }

    public synchronized void put(int element) throws InterruptedException {
        while (queue.size() == capacity) {
            // 队列已满，等待
            wait();
        }
        queue.offer(element);
        // 通知消费者可以取出元素
        notifyAll();
    }

    public synchronized int take() throws InterruptedException {
        while (queue.isEmpty()) {
            // 队列为空，等待
            wait();
        }
        int element = queue.poll();
        // 通知生产者可以放入元素
        notifyAll();
        return element;
    }

    public static void main(String[] args) {
        BlockingQueueExample blockingQueue = new BlockingQueueExample(5);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    blockingQueue.put(i);
                    System.out.println("Produced: " + i);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    int value = blockingQueue.take();
                    System.out.println("Consumed: " + value);
                    Thread.sleep(2000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}
